const co = require('co');
const logger = require('./builder.log');
const helper = require('./builder.helper');
const shell = require('./builder.shell');


let args = process.argv.splice(2);
if (!args || args.length < 1){
	logger.error("USAGE: node build.js  [appName]");
	return;
}

let appName = args[0];
if (!appName || appName.length == 0){
    logger.error("USAGE: node build.js  [appName]");
	return;
}
logger.notice("begin build: " + appName);

// Main =========================================


co(function *() {

    let result = 0;
    //检查执行路径
    result = yield shell.exec('ls dist');
    if(result === false){
        logger.error("dist目录不存在(请在根目录下执行，并确保存在 dist 目录)");
        return;
    }

    //读取配置参数
    let appConfig = yield helper.getAppConfig(appName);
	  console.log(appConfig);
    if (!appConfig){
        logger.error("读取App Config错误，请检查appName 输入是否正确，或是否已经正确配置 appConfig");
        return;
    }

    let srcPath = 'src/';
    let distPath = 'dist/' + appConfig.appName;

    //删除输出目录
    result = yield shell.exec(`rm -rf ${distPath}/*`);
    if(result === false){
        // 创建输出目录
        result = yield shell.exec(`mkdir ${distPath}`);
        if(result === false){
            logger.error("创建目录失败: " + distPath);
            return;
        }
    }

    //读取 pages 配置
    let appPages = yield helper.getAppPages(appConfig.id);
    if (!appPages){
        logger.error("读取App Pages错误，请检查是否已经正确配置 pages");
        return;
    }

	// 创建Pages目录
	result = yield shell.exec(`mkdir ${distPath}/pages`);
	if(result === false){
		logger.error("创建Pages目录失败: ${distPath}/pages" );
		return;
	}

	//生成 Pages
	const pageBuilder = require('./builder.pages');
	result = yield pageBuilder.build(distPath, appConfig, appPages);
	if(result === false){
		logger.error("生成Pages失败" );
		return;
	}


	// 创建assets目录
	result = yield shell.exec(`mkdir ${distPath}/assets`);
	if(result === false){
		logger.error("创建assets目录失败: ${distPath}/assets" );
		return;
	}


    //生成 manifest
	const manifestBuilder = require('./builder.manifest');
	result = yield manifestBuilder.build(distPath, appConfig, appPages);
	if(result === false){
		logger.error("生成manifest失败" );
		return;
	}

    //打包资源
	let resources = [
		'libs','services'
	];
	for (let i = 0; i < resources.length; i++){
		let resource = resources[i];
		result = yield shell.exec(`cp -r ${srcPath}/${resource}  ${distPath}/`);
	    if(result === false){
	        logger.error(`复制目录或文件失败:${srcPath}/${resource}`);
	        return;
	    }
	}

	//输出
	logger.log('');

	logger.success(`Build ${appName} 成功:`);
	logger.log(`============================`);
	logger.notice(`appName: ${appName}`);
	logger.notice(`appTitle: ${appConfig.appTitle}`);
	logger.notice(`小程序AppId: ${appConfig.wxAppId}`);
	logger.log(`============================`);
});
